var oCache = {
	iCacheLower: -1
};
var oTable;//Table Object
var isInitSearchData = false;
//--------------------------------------------
function fnSetKey( aoData, sKey, mValue )
{
	for ( var i=0, iLen=aoData.length ; i<iLen ; i++ )
	{
		if ( aoData[i].name == sKey )
		{
			aoData[i].value = mValue;
		}
	}
}

function fnGetKey( aoData, sKey )
{
	for ( var i=0, iLen=aoData.length ; i<iLen ; i++ )
	{
		if ( aoData[i].name == sKey )
		{
			return aoData[i].value;
		}
	}
	return null;
}
function renderLanguage(langKey){
	return ALL_LANG[langKey].title;
}
function renderCheckBox(key){
	return "<input type=\"checkbox\" value=\""+key+"\" class='chkbox' name='chkbox'>";
}
function renderCommand(key){
	return "<a id='edit_"+key+"' href=\"#\">Sửa</a>-<a id='delete_"+key+"' href=\"#\">Xóa</a>";
}
function renderParentTitle(title){
	return title==null?"[Gốc]":title;
}
function process_Data(dataresponse){
	var resultProcessData = [];
	for (i=0,iLength = dataresponse.length; i<iLength;i++){
		resultProcessData[i] = [];
		resultProcessData[i][0] = eval('i+1'); 
		resultProcessData[i][1] = renderCheckBox(dataresponse[i].categories_id); //Check Box
		resultProcessData[i][2] = renderCommand(dataresponse[i].categories_id); //Sua - Xoa
		resultProcessData[i][3] = dataresponse[i].categories_id; 
		resultProcessData[i][4] = dataresponse[i].categories_title; 
		resultProcessData[i][5] = renderParentTitle(dataresponse[i].parent_cat_title); 
		resultProcessData[i][6] = dataresponse[i].created; 
		resultProcessData[i][7] = renderLanguage(dataresponse[i].language); 
	}
	return resultProcessData;
} 

function fnDataTablesPipeline ( sSource, aoData, fnCallback ) {
	
	var iPipe = 5; /* Ajust the pipe size */
	
	var bNeedServer = false;
	var sEcho = fnGetKey(aoData, "sEcho");
	var iRequestStart = fnGetKey(aoData, "iDisplayStart");
	var iRequestLength = fnGetKey(aoData, "iDisplayLength");
	var iRequestEnd = iRequestStart + iRequestLength;
	oCache.iDisplayStart = iRequestStart;
	
	/* outside pipeline? */
	if ( oCache.iCacheLower < 0 || iRequestStart < oCache.iCacheLower || iRequestEnd > oCache.iCacheUpper )
	{
		bNeedServer = true;
	}
	
	/* sorting etc changed? */
	if ( oCache.lastRequest && !bNeedServer )
	{
		for( var i=0, iLen=aoData.length ; i<iLen ; i++ )
		{
			if ( aoData[i].name != "iDisplayStart" && aoData[i].name != "iDisplayLength" && aoData[i].name != "sEcho" )
			{
				if ( aoData[i].value != oCache.lastRequest[i].value )
				{
					bNeedServer = true;
					break;
				}
			}
		}
	}
	
	/* Store the request for checking next time around */
	oCache.lastRequest = aoData.slice();
	
	if ( bNeedServer )
	{
		if ( iRequestStart < oCache.iCacheLower )
		{
			iRequestStart = iRequestStart - (iRequestLength*(iPipe-1));
			if ( iRequestStart < 0 )
			{
				iRequestStart = 0;
			}
		}
		
		oCache.iCacheLower = iRequestStart;
		oCache.iCacheUpper = iRequestStart + (iRequestLength * iPipe);
		oCache.iDisplayLength = fnGetKey( aoData, "iDisplayLength" );
		fnSetKey( aoData, "iDisplayStart", iRequestStart );
		fnSetKey( aoData, "iDisplayLength", iRequestLength*iPipe );
		
		$.getJSON( sSource, aoData, function (json) { 
			//Process aoData
			json.aaData = process_Data(json.aaData);
			/* Callback processing */
			oCache.lastJson = jQuery.extend(true, {}, json);
			
			if ( oCache.iCacheLower != oCache.iDisplayStart )
			{
				json.aaData.splice( 0, oCache.iDisplayStart-oCache.iCacheLower );
			}
			json.aaData.splice( oCache.iDisplayLength, json.aaData.length );
			fnCallback(json);
			if (!isInitSearchData){
				isInitSearchData=true;
				initSearchArea();
			}
		} );
	}
	else
	{
		json = jQuery.extend(true, {}, oCache.lastJson);
		json.sEcho = sEcho; /* Update the echo for each response */
		json.aaData.splice( 0, iRequestStart-oCache.iCacheLower );
		json.aaData.splice( iRequestLength, json.aaData.length );
		fnCallback(json);
		return;
	}
}

(function($) {
	/*
	 * Function: fnGetColumnData
	 * Purpose:  Return an array of table values from a particular column.
	 * Returns:  array string: 1d data array 
	 * Inputs:   object:oSettings - dataTable settings object. This is always the last argument past to the function
	 *           int:iColumn - the id of the column to extract the data from
	 *           bool:bUnique - optional - if set to false duplicated values are not filtered out
	 *           bool:bFiltered - optional - if set to false all the table data is used (not only the filtered)
	 *           bool:bIgnoreEmpty - optional - if set to false empty values are not filtered from the result array
	 * Author:   Benedikt Forchhammer <b.forchhammer /AT\ mind2.de>
	 */
	$.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
		// check that we have a column id
		if ( typeof iColumn == "undefined" ) return new Array();
		
		// by default we only wany unique data
		if ( typeof bUnique == "undefined" ) bUnique = true;
		
		// by default we do want to only look at filtered data
		if ( typeof bFiltered == "undefined" ) bFiltered = true;
		
		// by default we do not wany to include empty values
		if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
		
		// list of rows which we're going to loop through
		var aiRows;
		
		// use only filtered rows
		if (bFiltered == true) aiRows = oSettings.aiDisplay; 
		// use all rows
		else aiRows = oSettings.aiDisplayMaster; // all row numbers

		// set up data array	
		var asResultData = new Array();
		
		for (var i=0,c=aiRows.length; i<c; i++) {
			iRow = aiRows[i];
			var aData = this.fnGetData(iRow);
			var sValue = aData[iColumn];
			
			// ignore empty values?
			if (bIgnoreEmpty == true && sValue.length == 0) continue;

			// ignore unique values?
			else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
			
			// else push the value onto the result data array
			else asResultData.push(sValue);
		}
		
		return asResultData;
	}}(jQuery));


function fnCreateSelect( aData )
{
	var r='<select><option value=""></option>', i, iLen=aData.length;
	for ( i=0 ; i<iLen ; i++ )
	{
		r += '<option value="'+aData[i]+'">'+aData[i]+'</option>';
	}
	return r+'</select>';
}


function initSearchArea(){    
    $("tfoot th").each( function ( i ) {
		if (i==0||i==1||i==2||i==3||i==6||i==7) return;
		this.innerHTML = fnCreateSelect( oTable.fnGetColumnData(i) );
		$('select', this).change( function () {
			oTable.fnFilter( $(this).val(), i );
		} );
	} );
}
$(document).ready(function(){
	//-------------- Khoi Tao Table
	    oTable = $('#catelist_id').dataTable({
		"bJQueryUI": true,
		"sPaginationType": "full_numbers",
		"bProcessing": true,
		"bServerSide": true,
		"sAjaxSource": BASE_URL+"/clip/getcatlist",
		"fnServerData": fnDataTablesPipeline,
		"oLanguage": {
			"sProcessing": "Tải dữ liệu...",
			"sLengthMenu": "Hiện thị _MENU_",
			"sZeroRecords": "Không có danh mục nào.",
			"sInfo": "_START_ - _END_ trong _TOTAL_ danh mục",
			"sInfoEmpty": "Danh sách rỗng ",
			"sInfoFiltered": "(không tìm thấy trong _MAX_ danh mục)",
			"sInfoPostFix": "",
			"sSearch": "Tìm kiếm",
			"oPaginate": {
				"sFirst":    "Trang đầu",
				"sPrevious": "<<",
				"sNext":     ">>",
				"sLast":     "Trang cuối"
			}
		},
		"aoColumnDefs": [ 
			{ "bSortable": false, "aTargets": [ 2,1,0,7 ] }			
		],
		"aoColumns": [
		     null,
		     null,
		     null,
  			{ "sName": "categories_id" },
  			{ "sName": "categories_title" },
  			{ "sName": "parent_cat_title" },
  			{ "sName": "created" },
  			{ "sName": "language" }
  		]
	});
	    
	//------------------------------------
	$("#check_all").change(function(){
		if ($(this).is(':checked')){
			$(".chkbox").attr('checked',true);
		} else {
			$(".chkbox").attr('checked',false);
		}
	});
	//Load Gia Tri Mac Dau Tien Cho Categories
})
